import {
	BASE_URL
} from '@/config/index.js'
/**
 * 提示方法
 * @param {String} title 提示文字
 * @param {String}  icon icon图片
 * @param {Number}  duration 提示时间
 */
export function toast(title, icon = 'none', duration = 1500) {
	if (title) {
		uni.showToast({
			title,
			icon,
			duration
		})
	}
}

/**
 * 设置缓存
 * @param {String} key 键名
 * @param {String} data 值
 */
export function setStorageSync(key, data) {
	uni.setStorageSync(key, data)
}

/**
 * 获取缓存
 * @param {String} key 键名
 */
export function getStorageSync(key) {
	return uni.getStorageSync(key)
}

/**
 * 删除缓存
 * @param {String} key 键名
 */
export function removeStorageSync(key) {
	return uni.removeStorageSync(key)
}

/**
 * 清空缓存
 * @param {String} key 键名
 */
export function clearStorageSync() {
	return uni.clearStorageSync()
}


/**
 * 页面跳转
 * @param {'navigateTo' | 'redirectTo' | 'reLaunch' | 'switchTab' | 'navigateBack' | number } url  转跳路径
 * @param {String} params 跳转时携带的参数
 * @param {String} type 转跳方式
 **/
export function useRouter(url, params = {}, type = 'navigateTo') {
	try {
		if (Object.keys(params).length) url = `${url}?data=${encodeURIComponent(JSON.stringify(params))}`
		if (type === 'navigateBack') {
			// uni[type]({
			// 	delta: url
			// })
			uni.navigateBack({
				delta: url
			})
		}
		if (type === 'navigateTo') {
			uni.navigateTo({
				url
			})
		}
		if (type === 'redirectTo') {
			uni.redirectTo({
				url
			})
		}
		if (type === 'reLaunch') {
			uni.reLaunch({
				url
			})
		}
		if (type === 'switchTab') {
			uni.switchTab({
				url
			})
		}

		// else {

		// 	uni[type]({
		// 		url
		// 	})
		// }
	} catch (error) {
		console.error(error)
	}
}

/**
 * 预览图片
 * @param {Array} urls 图片链接
 */
export function previewImage(urls, itemList = ['发送给朋友', '保存图片', '收藏']) {
	uni.previewImage({
		urls,
		longPressActions: {
			itemList,
			fail: function(error) {
				console.error(error, '===previewImage')
			}
		}
	})
}

/**
 * 保存图片到本地
 * @param {String} filePath 图片临时路径
 **/
export function saveImage(filePath) {
	if (!filePath) return false
	uni.saveImageToPhotosAlbum({
		filePath,
		success: (res) => {
			toast('图片保存成功', 'success')
		},
		fail: (err) => {
			if (err.errMsg === 'saveImageToPhotosAlbum:fail:auth denied' || err.errMsg ===
				'saveImageToPhotosAlbum:fail auth deny') {
				uni.showModal({
					title: '提示',
					content: '需要您授权保存相册',
					showCancel: false,
					success: (modalSuccess) => {
						uni.openSetting({
							success(settingdata) {
								if (settingdata.authSetting['scope.writePhotosAlbum']) {
									uni.showModal({
										title: '提示',
										content: '获取权限成功,再次点击图片即可保存',
										showCancel: false
									})
								} else {
									uni.showModal({
										title: '提示',
										content: '获取权限失败，将无法保存到相册哦~',
										showCancel: false
									})
								}
							},
							fail(failData) {
								console.log('failData', failData)
							}
						})
					}
				})
			}
		}
	})
}

/**
 * 深拷贝
 * @param {Object} data
 **/
export const clone = (data) => JSON.parse(JSON.stringify(data))

function base64ToBlob(base64) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime,
	});
}

function translate(imgSrc, scale) {
	//imgSrc:图片的路径
	//scale:缩放比例 0-1之间
	return new Promise((reslove, reject) => {
		var img = new Image(); //创建Image对象生成一个<img>标签
		img.src = imgSrc; //将图片路径赋给<img>标签的src
		img.onload = () => { //onload在图片加载成功后触发，在onload中完成压缩功能
			var h = img.height / 2; // 获取原本图片的宽高
			var w = img.width / 2; //默认按比例压缩,根据需求修改
			var canvas = document.createElement('canvas'); //创建画布
			var ctx = canvas.getContext('2d'); //设置为2d效果
			var width = document.createAttribute("width"); //创建属性节点
			width.nodeValue = w; //设置属性值
			var height = document.createAttribute("height");
			height.nodeValue = h;
			canvas.setAttributeNode(width); //设置画布宽高
			canvas.setAttributeNode(height);
			ctx.drawImage(img, 0, 0, w, h); //将图片贴到画布上
			//img:图片 0,0:粘贴的位置 w,h:粘贴图片的大小
			var base64 = canvas.toDataURL('image/png', scale);
			//'image/png':压缩返回图片的类型 scale:图片质量
			//如果要base64的流，可以直接将结果返回了
			canvas = null; //清除画布
			var blob = base64ToBlob(base64); //需要二进制流调用该方法拿到
			// let blobUrl = window.URL.createObjectURL(blob); //blob地址
			reslove(new window.File(
				[blob],
				'upload.png', {
					type: 'image/png'
				}
			))
		}
	})
}
// base64转Blob


/**
 * 上传图片
 */
export const uploadPic = (file, obj) => {
	const _url = obj?.url || `${BASE_URL}/system/user/profile/avatar`
	const _beforeLoadingTitle = obj?.beforeLoadingTitle || '上传中...'
	const _afterLoadingTitle = obj?.afterLoadingTitle || '上传成功'
	const _faileTitle = obj?.faileTitle || '上传失败'
	const _maxSize = obj?.maxSize || 5
	return new Promise((resolve, reject) => {
		const tempFilePaths = file.tempFilePaths;
		uni.showLoading({
			title: _beforeLoadingTitle,
		});
		translate(tempFilePaths[0], 0.85).then(compressBlob => {
			console.log('compressBlob', compressBlob)
			let resSize = compressBlob.size / (1024 * 1024);
			console.log('resSize', resSize)
			if (resSize > _maxSize) {
				toast(`上传图片大小不能超过${_maxSize}MB`, 'error')
				resolve({
					isSuccess: false
				})
			} 
			else{
				uni.uploadFile({
					url: _url, //上传图片api
					file: compressBlob,
					name: 'avatarfile',
					header: {
						"authorization": getStorageSync("token")
					},
					success: (res) => {
						let group = JSON.parse(res.data)
						uni.hideLoading()
				
						if (group.code == 200) {
							toast(_afterLoadingTitle)
							resolve({
								isSuccess: true,
								data: group.data
							})
						} else if (group.code == 401) {
							clearStorageSync()
							useRouter('/pages/login/login', 'reLaunch')
						} else {
							resolve({
								isSuccess: false
							})
				
							toast(_faileTitle)
						}
					},
					fail() {
				
						toast(_faileTitle)
						reject({
							isSuccess: false
						})
					}
				});
						
			}
			
		})
	})
}

/**
 * 上传图片
 */
export const chooseImg = (obj) => {

	const _url = obj?.url || `${BASE_URL}/app/vote/tWxUserinfo/uploadImage`
	const _beforeLoadingTitle = obj?.beforeLoadingTitle || '上传中...'
	const _afterLoadingTitle = obj?.afterLoadingTitle || '上传成功'
	const _faileTitle = obj?.faileTitle || '上传失败'

	const _maxSize = obj?.maxSize || 1
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1, // 图片数量
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择或者拍照
			success: (res) => {
				const tempFilePaths = res.tempFilePaths;
				console.log(tempFilePaths[0])
				let resSize = tempFilePaths[0].size / (1024 * 1024);
				if (resSize > _maxSize) {
					toast(`上传图片大小不能超过${maxSize}MB`, 'error')
					resolve({
						isSuccess: false
					})
				} else {
					uni.showLoading({
						title: _beforeLoadingTitle,
					});
					uni.uploadFile({
						url: _url, //上传图片api
						filePath: tempFilePaths[0],
						name: 'file',
						header: {
							"Authorization": getStorageSync("token")
						},
						success: (res) => {
							let group = JSON.parse(res.data)
							uni.hideLoading()
							if (group.code == 200) {
								toast(_afterLoadingTitle)
								resolve({
									isSuccess: true,
									data: group.data
								})
							} else if (group.code == 401) {
								clearStorageSync()
								useRouter('/pages/login/login', 'reLaunch')
							} else {
								resolve({
									isSuccess: false
								})
								toast(_faileTitle)
							}
						},
						fail() {
							toast(_faileTitle)
							reject({
								isSuccess: false
							})
						}
					});

				}
			}
		});

	})

}

export const checkVoteEndTime = (voteEndTime) => {
	console.log("isNaN(new Date(voteEndTime))", isNaN(new Date(voteEndTime)))
	if (isNaN(new Date(voteEndTime))) {
		return {
			flag: false,
			msg: '投票结束时间格式不正确'
		}
	}
	// 获取当前时间  
	let now = new Date();
	// 判断投票结束时间是否在当前时间之后  
	if (new Date(voteEndTime) < now) {
		return {
			flag: false,
			msg: '投票结束时间不能小于当前时间'
		}
	}
	// 判断投票结束时间是否超过一个月后的时间  
	let oneMonthLater = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate());
	if (voteEndTime > oneMonthLater) {
		return {
			flag: false,
			msg: '投票结束时间不能超过一个月后的时间'
		};
	}
	return {
		flag: true
	}

}
export const compareDateTime = (voteEndTime) => {
	const _date = new Date();
	const _voteEndTime = new Date(voteEndTime);

	if (_date.getTime() > _voteEndTime.getTime()) {
		return false
	} else {
		return true;
	}
}